import { defineStore } from "pinia";
import request from '@/utils/request'
import {ResApi} from '@/types/data'
import {CartItem} from '@/types/cart'

const useCartStore = defineStore('cart',{
  // 状态
  state: () => ({
    // 购物车列表
    list: [] as CartItem[],
  }),
  
  actions: {
    // 加入购物车
    async addCart(skuId:string,count:number){
      const res = await request.post('/member/cart',{skuId,count})

      this.getCartList()
    },

    // 获取购物车列表数据
    async getCartList(){
      const res = await request.get<ResApi<CartItem[]>>('/member/cart')
      this.list = res.data.result
    },

    // 根据skuIds删除购物车数据
    async delCartList(skuIds:string[]){
      await request.delete('/member/cart',{data:{ids:skuIds}})
      this.getCartList()
    },


    // 修改sku的状态或数量
    async updateCart(skuId:string,data:{selected?:boolean;count?:number}){
      await request.put(`/member/cart/${skuId}`,data)
      this.getCartList()
    },

    // 修改所有的sku的状态
    async updateAllSelected(selected:boolean){
        await request.put('/member/cart/selected',{
          selected
        })
        this.getCartList()
    },

    // 清空购物车数据
    clear(){
      this.list = []
    }

  },
  // 计算
  getters: {
    effectiveList():CartItem[]{
      return this.list.filter((item:CartItem)=>{
        return item.isEffective && item.stock>0
      })
    },
    effectiveListCount():number{
      return this.effectiveList.reduce((acc:number,item:CartItem)=>{
         return acc + item.count
      },0)
    },

    effectiveListPrice():string{
      return this.effectiveList.reduce((acc:number,item:CartItem)=>{
        return acc + item.count * +item.nowPrice
      },0).toFixed(2)
    },

    // 判断是否全部选中状态
    isAllSelected():boolean{
      return this.effectiveList.length>0 && this.effectiveList.every((item:CartItem)=>item.selected)
    },

    // ---------------------------
    selectedCartList():CartItem[]{
      return this.effectiveList.filter(item=>item.selected)
    },
    selectedCartListCount():number{
      return this.selectedCartList.reduce((acc,item)=>{
         return acc+item.count
      },0)
    },
    selectedCartListPrice():string{
      return this.selectedCartList.reduce((acc:number,item:CartItem)=>{
        return acc+ item.count * +item.nowPrice
     },0).toFixed(2)
    }

  }
 
});

export default useCartStore;